package com.ksd.quartz.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;

public class DRMHttpClient {
	private static final Logger logger = LoggerFactory.getLogger(DRMHttpClient.class);
	public static String udrmHttpDoPost(String url, String requestData) {
		BasicHttpClientConnectionManager connManager = null;
		try {
			connManager = new BasicHttpClientConnectionManager(
					RegistryBuilder.<ConnectionSocketFactory>create()
							.register("http", PlainConnectionSocketFactory.getSocketFactory())
							.register("https", new SSLConnectionSocketFactory(
									SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
									NoopHostnameVerifier.INSTANCE))
							.build(),
					null,
					null,
					null
			);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();
        HttpPost httpPost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        httpPost.setConfig(requestConfig);

        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
        httpPost.addHeader("Cache-Control", "no-cache");
        StringEntity postEntity = new StringEntity(requestData, "UTF-8");
        httpPost.setEntity(postEntity);

        HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpPost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		}
        HttpEntity httpEntity = httpResponse.getEntity();
        try {
			return  EntityUtils.toString(httpEntity, "UTF-8");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		}
	}


	public static String udrmHttpDoPostOutTime(String url, String requestData) throws Exception {
		BasicHttpClientConnectionManager connManager = null;
			connManager = new BasicHttpClientConnectionManager(
					RegistryBuilder.<ConnectionSocketFactory>create()
							.register("http", PlainConnectionSocketFactory.getSocketFactory())
							.register("https", new SSLConnectionSocketFactory(
									SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
									NoopHostnameVerifier.INSTANCE))
							.build(),
					null,
					null,
					null
			);

		HttpClient httpClient = HttpClientBuilder.create()
				.setConnectionManager(connManager)
				.build();
		HttpPost httpPost = new HttpPost(url);

		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
		httpPost.setConfig(requestConfig);

		httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
		httpPost.addHeader("Cache-Control", "no-cache");
		StringEntity postEntity = new StringEntity(requestData, "UTF-8");
		httpPost.setEntity(postEntity);

		HttpResponse httpResponse = null;
			httpResponse = httpClient.execute(httpPost);

		HttpEntity httpEntity = httpResponse.getEntity();
			return  EntityUtils.toString(httpEntity, "UTF-8");

	}

	public static void udrmHttpDoPostNoResponse(String url, String requestData) {
		BasicHttpClientConnectionManager connManager = null;
		try {
			connManager = new BasicHttpClientConnectionManager(
					RegistryBuilder.<ConnectionSocketFactory>create()
							.register("http", PlainConnectionSocketFactory.getSocketFactory())
							.register("https", new SSLConnectionSocketFactory(
									SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
									NoopHostnameVerifier.INSTANCE))
							.build(),
					null,
					null,
					null
			);

			HttpClient httpClient = HttpClientBuilder.create()
					.setConnectionManager(connManager)
					.build();
			HttpPost httpPost = new HttpPost(url);

			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
			httpPost.setConfig(requestConfig);

			httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
			httpPost.addHeader("Cache-Control", "no-cache");
			StringEntity postEntity = new StringEntity(requestData, "UTF-8");
			httpPost.setEntity(postEntity);
			HttpResponse httpResponse = null;
			httpResponse = httpClient.execute(httpPost);

		} catch (Exception e) {

		}

	}


	public static DRMHttpResponse udrmHttpDoPost(String url, String requestData, Map<String, String> extHeader) {
		BasicHttpClientConnectionManager connManager = null;
		try {
			connManager = new BasicHttpClientConnectionManager(
					RegistryBuilder.<ConnectionSocketFactory>create()
							.register("http", PlainConnectionSocketFactory.getSocketFactory())
							.register("https", new SSLConnectionSocketFactory(
									SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
									NoopHostnameVerifier.INSTANCE))
							.build(),
					null,
					null,
					null
			);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		HttpClient httpClient = HttpClientBuilder.create()
				.setConnectionManager(connManager)
				.build();
		HttpPost httpPost = new HttpPost(url);

		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
		httpPost.setConfig(requestConfig);
		httpPost.addHeader("Content-Type", "application/json");

		Iterator<Map.Entry<String, String>> iter = extHeader.entrySet().iterator();
		while(iter.hasNext()) {
			Map.Entry<String, String> entry = iter.next();
			httpPost.addHeader(entry.getKey(), entry.getValue());
		}

		StringEntity postEntity = new StringEntity(requestData, "UTF-8");
		httpPost.setEntity(postEntity);

		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpPost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		DRMHttpResponse drmHttpResponse = new DRMHttpResponse();
		HttpEntity httpEntity = httpResponse.getEntity();
		try {
			int responseStatusCode = httpResponse.getStatusLine().getStatusCode();
			logger.info("udrmHttpDoPost response status code : " + responseStatusCode);  //401

			drmHttpResponse.setResponseCode(responseStatusCode);
			drmHttpResponse.setResponseBody(EntityUtils.toString(httpEntity, "UTF-8"));

//			logger.info("udrmHttpDoPost response data :"+drmHttpResponse.toString());
			return  drmHttpResponse;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	public static DRMHttpResponse udrmHttpDoPost2(String url, String requestData, Map<String, String> extHeader) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
		BasicHttpClientConnectionManager connManager = null;

		logger.info("发送请求地址:"+url);
		connManager = new BasicHttpClientConnectionManager(
				RegistryBuilder.<ConnectionSocketFactory>create()
						.register("http", PlainConnectionSocketFactory.getSocketFactory())
						.register("https", new SSLConnectionSocketFactory(
								SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
								NoopHostnameVerifier.INSTANCE))
						.build(),
				null,
				null,
				null
		);

		HttpClient httpClient = HttpClientBuilder.create()
				.setConnectionManager(connManager)
				.build();
		HttpPost httpPost = new HttpPost(url);

		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
		httpPost.setConfig(requestConfig);
		httpPost.addHeader("Content-Type", "application/json");

		Iterator<Map.Entry<String, String>> iter = extHeader.entrySet().iterator();
		while(iter.hasNext()) {
			Map.Entry<String, String> entry = iter.next();
			httpPost.addHeader(entry.getKey(), entry.getValue());
		}

		StringEntity postEntity = new StringEntity(requestData, "UTF-8");
		httpPost.setEntity(postEntity);

		HttpResponse httpResponse = null;

		httpResponse = httpClient.execute(httpPost);

		DRMHttpResponse drmHttpResponse = new DRMHttpResponse();
		HttpEntity httpEntity = httpResponse.getEntity();

		int responseStatusCode = httpResponse.getStatusLine().getStatusCode();
		logger.info("udrmHttpDoPost response status code : " + responseStatusCode);

		drmHttpResponse.setResponseCode(responseStatusCode);
		drmHttpResponse.setResponseBody(EntityUtils.toString(httpEntity, "UTF-8"));

		logger.info("udrmHttpDoPost response data :"+drmHttpResponse.toString());
		return  drmHttpResponse;
	}

	public static String udrmHttpDoGet(String url, String requestData) {
		url = url + "?" + requestData;
		try {
			URL targetUrl = new URL(url);
			HttpURLConnection httpConnect = (HttpURLConnection) targetUrl
					.openConnection();
			httpConnect.setDoOutput(true);
			httpConnect.setDoInput(true);
			httpConnect.setRequestMethod("GET");
			httpConnect.setRequestProperty("Content-Type", "application/json");
			httpConnect.setConnectTimeout(3000);
			httpConnect.connect();
			if (httpConnect.getResponseCode() != 200) {
				return null;
			}
			InputStream in = httpConnect.getInputStream();
			byte[] responseData = read(in);
			String response = new String(responseData,"utf-8");
			in.close();
			httpConnect.disconnect();
			return response;
		} catch (IOException e) {
			logger.error(e.toString());
			return null;
		}
	}

	public static byte[] read(InputStream is) {
		byte[] dateByte = new byte[204800];
		byte[] dataTemp = new byte[8192];
		int len = 0;
		int totalLen = 0;
		try {
			while ((len = is.read(dataTemp)) > 0) {
				System.arraycopy(dataTemp, 0, dateByte, totalLen, len);
				totalLen += len;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		byte[] recvData = new byte[totalLen];
		System.arraycopy(dateByte, 0, recvData, 0, totalLen);
		return recvData;
	}
}